﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using _404park.Core.Crawler;

namespace _404park.ApplicationServices.Crawler.Parser
{
    public abstract class BaseRSSFeedParser : BaseFeedParser
    {
        protected internal override IList<Feed> ParseFeed(string data)
        {
            var feedList = new List<Feed>();
            var xmlDoc = XDocument.Parse(data);
            if (xmlDoc.Root != null)
            {
                var xmlns = xmlDoc.Root.GetDefaultNamespace();
                xmlDoc.Root.Descendants(xmlns + "item").ToList().ForEach(element => feedList.Add(CreateFeedItem(element, xmlns)));
            }
            return feedList;
        }

        private Feed CreateFeedItem(XElement xElement, XNamespace xmlns)
        {

            var title = xElement.Element(xmlns + "title") != null ? xElement.Element(xmlns + "title").Value : string.Empty;
            var description = xElement.Element(xmlns + "description") != null ? xElement.Element(xmlns + "description").Value : string.Empty;
            var clickUrl = xElement.Element(xmlns + "link") != null ? xElement.Element(xmlns + "link").Value : string.Empty;

            var feed = new Feed
            {
                Title = title,
                Description = description,
                ClickUrl = clickUrl,
                DisplayUrl = string.Empty
            };
            return feed;
        }
    }
}
